package main

import (
	"net"
	"fmt"
	"os"
	"log"
	"chatServer/protocol"
)

func CheckError(err error) {
	if err !=nil{
		fmt.Fprintf(os.Stderr,"Fatal error:$s",err.Error())
		os.Exit(1)
	}
}

func Log(v ...interface{})  {
	log.Println(v...)
}

func handleConnection(conn net.Conn) {
	buffer:=make([]byte,2048)
	for  {
		n,err:=conn.Read(buffer)
		if err !=nil{
			Log(conn.RemoteAddr().String()," connection error:",err)
			return
		}
		Log(conn.RemoteAddr().String(),"receive data string:\n",string(buffer[:n]))
	}
}

func reader(readerChannel chan []byte) {
	for{
		select {
		case data:=<- readerChannel:
			Log(string(data))
		}
	}
}

func handleProtocalConnection(conn net.Conn) {
	//缓冲区，存储被截断的数据
	tmpBuffer:=make([]byte,0)
	//接收解包
	readerChannel:=make(chan []byte,16)
	go reader(readerChannel)

	buffer:=make([]byte,1024)
	for {
		n,err:=conn.Read(buffer)
		if err !=nil{
			Log(conn.RemoteAddr().String()," connection error:%s",err.Error())
			return
		}
		tmpBuffer=protocol.Depack(append(tmpBuffer,buffer[:n]...),readerChannel)
	}
	defer conn.Close()
}

func main() {
	//建立socket,监听端口
	netListen,err:=net.Listen("tcp","localhost:6060")
	CheckError(err)
	defer netListen.Close()
	Log("Waiting for clients connet")
	for{
		conn,err:=netListen.Accept()
		if err !=nil{
			continue
		}
		Log(conn.RemoteAddr().String(),"tcp connect success")
		//go handleConnection(conn)
		go handleProtocalConnection(conn)
	}
}